package com.topway.dsmflex.services.synchro;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import com.Consts;
import com.topway.dsmflex.dao.synchro.SqlDao;
import com.topway.dsmflex.dao.synchro.TableDao;
import com.topway.dsmflex.model.synchro.DataColumnBean;
import com.topway.dsmflex.model.synchro.DataSourceBean;
import com.topway.dsmflex.model.synchro.DataSqlBean;
import com.topway.dsmflex.model.synchro.DataTableBean;
import com.topway.dsmflex.services.synchro.base.AbstractBaseServices;
import com.topway.dsmflex.util.ConvertUtil;





/**
 * 
 * @author liusy 2013-05-8
 *
 */
public class SqlServices extends AbstractBaseServices<DataSqlBean>{

	public SqlServices(String dataFilePath) {
		super(dataFilePath);
		this.sqlDao = SqlDao.getSqlDao();
		this.tableDao = TableDao.getTableDao();
		this.tableServices = TableServices.getTableServices();
		// TODO Auto-generated constructor stub
	}
	
	private SqlDao sqlDao = new SqlDao();
	private static SqlServices sqlServices = new SqlServices(Consts.DATAFILE_SQL);
	private TableServices tableServices = null;
	protected TableDao tableDao = null;

	
	public synchronized static SqlServices getSqlServices()
	{
		return sqlServices;
	}
	public List<DataColumnBean> getColumnInfo(DataTableBean dt)
	{
	 	List<DataColumnBean> dcListT = new ArrayList<DataColumnBean>();
	 	try {
	 	dcListT = (List<DataColumnBean>) sqlDao.getColumnInfo(dt.getSourceDataSource(), dt.getSelectSourceSql());
	 	this.setSourceColumn(tableDao.getSourceColumn());
	 	if(mapTable.containsKey( dt.getTableNameSource()))
	 	{
	 		DataTableBean _dt = mapTable.get( dt.getTableNameSource());
	 		List<DataColumnBean> dcListS = _dt.getDataColumnBean();
	 		if(null==dcListS || dcListS.size()==0)
	 			return dcListT;
	 		DataColumnBean dcT;
	 		DataColumnBean dcS;
			for (int j = 0; j < dcListT.size(); j++) {
				dcT = dcListT.get(j);
		 		for (int i = 0; i < dcListS.size(); i++) {
					dcS = dcListS.get(i);
					if(dcT.getColumnNameSource().equals(dcS.getColumnNameSource()))
						try {
							ConvertUtil.convertToPool(dcT, dcS);
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
			}
	 	}
		} catch (Exception e) {
			e.printStackTrace();
		}
	 	return dcListT;
    }
	
	public List<DataSqlBean> getAllDataTable(DataSourceBean  dsSource) {
		List<DataSqlBean> list= new ArrayList<DataSqlBean>();
    	for (Entry<String, DataSqlBean> entry : mapTable.entrySet()) {
    		list.add(entry.getValue());
    	}	
    	return list;
	}
	
	public String [] getTargetTablesByDb(DataSqlBean dt)
	{
		return tableServices.getTargetTablesByDb(dt);
	}
	
	public String [] getColumnInfoArray(DataSqlBean dt)
	{
		return tableServices.getColumnInfoArray(dt);
    }
	
}
